<template>
  <!-- 现金流量表 -->
    <div class="tobeDone">
        <div class="search-wrap m-b20 d-flex j-end">
          <el-button @click="addCashFlow" class="button_edit">新增现金流量表</el-button>
          <el-button @click="adCategory" class="button_edit">新增营收分类</el-button>
          <el-button @click="importExcel" class="button_edit">导入</el-button>
          <el-button @click="onExport" class="button_edit">导出</el-button>
          <el-button @click="templateDownload" class="button_edit">模版下载</el-button>
        </div>
        <public-table
                ref="publicTableRef"
                index
                :selection="false"
                :is-paging="false"
                :indexWidth="'100'"
                :page="page"
                border
                :header-cell-style="{'background':'#f7f7fa'}"
                :tree-props="treeProps"
                row-key="categoryId"
                :tableData="tableData"
                :tableOption.sync="tableOption"
        >
            <template #buttons="scope">
                <el-button
                        v-if="scope.row.parentId!=='0' && scope.row.childList===null"
                        class="button_edit m-b5 m-r10"
                        @click="onEditCategory(scope.row)"
                >编辑类别</el-button>
                <el-button
                        v-if="scope.row.parentId!=='0' && scope.row.childList===null"
                        class="button_edit m-b5 m-r10"
                        @click="onEditAmount(scope.row)"
                >编辑金额</el-button>
                <svg-icon
                        icon-class="delete-icon"
                        class="delete-icon"
                        @click="onDelete(scope.row)"
                ></svg-icon>
            </template>
            <template #categoryName="scope">
                <span :style="{fontWeight:scope.row.parentCategoryName!==null?'':' 600'}">{{scope.row.categoryName}}</span>
            </template>
            <template #parentCategoryName="scope">
                <span style="font-weight: 600;">{{scope.row.parentCategoryName  || '-'}}</span>
            </template>
        </public-table>
    </div>

    <!--  新增现金流量表  -->
    <public-form-popup
            ref="publicFormPopupRef"
            popup-type="add"
            :popup-params="{
              width:'40%',
              title:'新增现金流量表',
              loadingText:'表单数据提交中...',
              confirmButtonTitle:'确认'
            }"
            :fields="fields"
            :formParams="{
                formLabelWidth:'90px'
            }"
            :form="cashflowStatementForm"
            :confirm-params="{
                fun:(form,isLoading)=>{
                  onCashflowStatementConfirm(form,isLoading)
                }
            }"
      />

    <!-- 新增营收分类   -->
    <public-form-popup
            ref="publicFormPopupRef2"
            :popup-params="{
              width:'40%',
              title:'新增营收类别',
              loadingText:'表单数据提交中...',
              confirmButtonTitle:'确认'
            }"
            :form="categoryForm"
            :fields="categoryFields"
            :confirm-params="{
                /* interfaceConfig:{
                    fileName:'investment',
                    apiPath:'investmentProjects.addCategory',
                    defaultParams:{
                        projectId:getProjectId
                    }
                },*/
                fun:(form,isLoading)=>{
                  let params = {
                      categoryName:form.categoryName,
                      parentId:form.parentId,
                      projectId:form.projectId || getProjectId,
                      status:form.status,
                      remark:form.remark || '',
                      sort:form.sort || '',
                  }
                  isLoading.value = true;
                  addCategory(params,()=>{
                      ElMessage.success('新增营收分类成功');
                      getCategory();
                      getRevenuePage(getProjectId);
                      isLoading.value = false;
                      publicFormPopupRef2.close();
                  },
                  ()=>{
                      ElMessage.error('新增营收分类失败!');
                      isLoading.value = false;
                      publicFormPopupRef2.value.close();
                  });
                }
            }"
            popup-type="add"
    />

    <!-- 编辑营收类别   -->
    <public-form-popup
            ref="publicFormPopupRef3"
            popup-type="edit"
            :popup-params="{
              width:'40%',
              title:'编辑营收类别',
              loadingText:'表单数据提交中...',
              confirmButtonTitle:'确认'
            }"
            :form="editCategoryForm"
            :fields="editCategoryFields"
            :confirm-params="{
                 fun:(form,isLoading)=>{
                     let params = {
                         projectId:form.projectId,
                         categoryId:form.categoryId,
                         categoryName:form.categoryName
                     }
                     isLoading.value = true;
                     editCategory(params,()=>{
                          isLoading.value = false;
                          publicFormPopupRef3.close();
                          ElMessage.success('修改成功!');
                          getCategory();
                          getRevenuePage(getProjectId);
                     },()=>{
                          isLoading.value = false;
                          publicFormPopupRef3.close();
                          ElMessage.error('修改失败!');
                     });
                 }
            }"
    />

    <!-- 编辑现金流量   -->
    <edit-revenue-amount-popup
            ref="editAmountPopupRef"
            @on-success="onSuccess"
    />

  <!-- 删除现金流量 -->
  <del-project-investment-revenue-popup
          ref="delProjectInvestmentRevenuePopupRef"
          @on-success="onSuccess"
  />

  <!-- 导入excel   -->
    <public-dialog
            :title="'导入现金流量表'"
            :width="'40%'"
            :confirmButtonTitle="'确认'"
            v-model:visible="visible"
            @onConfirm="onConfirm"
    >
        <div class="public-dialog-content d-flex flex-column">
            <el-upload
                    ref="uploadRef"
                    class="upload-demo"
                    drag
                    action="#"
                    multiple
                    :http-request="uploadFile"
            >
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">
                    将文件拖到此处或<em>点击上传</em>
                </div>
            </el-upload>
        </div>
    </public-dialog>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue'
import { useRouter } from 'vue-router'
import PublicTable from "@/components/PublicTable";
import {costEstimationApi, investmentProjects} from "@/api/investment";
import PublicFormPopup from "@/components/publicFormPopup";
import EditRevenueAmountPopup from "./components/editRevenueAmountPopup";
import DelProjectInvestmentRevenuePopup from "./components/delProjectInvestmentRevenuePopup"
import {ElLoading, ElMessage, ElMessageBox, ElUpload} from "element-plus";
import {exportExcelFile, limitInputNum} from "@/common/utils/GlobalUtils";
import PublicDialog from "@/components/PublicDialog.vue";
import {UploadFilled} from "@element-plus/icons-vue";
import {retirementApi} from "@/api/businessFinance";

const router = useRouter();
const getProjectId  = router.currentRoute.value.params.projectId;
const getProjectName  = router.currentRoute.value.params.projectName;


const page = reactive({
    total: 0,
    current: 1,
    size: 10,
});

const tableOption = ref([]);

const treeProps = reactive({
    children:'childList'
});

const tableData = ref([]);
const cashflowStatementForm = ref({});

const fields = ref([
    {
        label:'项目名称',
        type:'input',
        key:'projectName',
        required: false,
        disabled:true,
        placeholder:getProjectName,
        message:'请输入项目名称',
        event:'blur',
    },
    {
        label: '年度',
        type:'year',
        key:'year',
        placeholder:'请选择年度',
        message:'请选择年度',
        event:'change'
    },
    {
        label: '金额',
        type:'input',
        key:'amount',
        placeholder:'请输入金额',
        message:'请输入金额',
        event:'blur',
        fun:(e)=>{cashflowStatementForm.value['amount'] = limitInputNum(cashflowStatementForm.value['amount'],6,0,false)}
    },
    /*{
        label: '科目类别',
        type:'select',
        key:'categoryId',
        width:300,
        clearable:true,
        placeholder:'请选择科目类别',
        message:'请选择科目类别',
        event:'change',
        options:{
            labelKey:'categoryName',
            valueKey:'categoryId',
            list:[]
        },
        interfaceConfig:{
            fileName:'investment',
            apiPath:'investmentProjects.getCategory',
            param:{
                projectId:getProjectId
            }
        }
    },*/
    {
        label:'科目类别',
        type:'cascader',
        key:'categoryId',
        required: true,
        message:'请选择科目类别',
        placeholder:'请选择科目类别',
        options:[],
        props:{
            lazy: true,
            emitPath:false,
            checkStrictly: true,// 设置父子节点取消选中关联，从而达到选择任意一级选项的目的
            async lazyLoad(node, resolve) {
                const { level } = node;
                try {
                    if(level === 0){
                        const res = await investmentProjects.getCategory({projectId:getProjectId,pid:0});
                        let nodes = [];
                        res.data.forEach(item=>{
                            nodes.push({
                                // value: item.projectId+'_'+item.categoryId,
                                value: item.categoryId,
                                label: item.categoryName,
                                leaf: level >= 3
                            })
                        });
                        resolve(nodes)
                    }
                    if(level > 0){
                        // const res = await investmentProjects.getCategory({projectId:getProjectId,pid:node.value.split('_')[1]});
                        const res = await investmentProjects.getCategory({projectId:getProjectId,pid:node.value});
                        let nodes = [];
                        res.data.forEach(item=>{
                            nodes.push({
                                value: item.categoryId,
                                label: item.categoryName,
                                leaf: level >= 3
                            })
                        });
                        resolve(nodes)
                    }
                }catch (e) {
                    let nodes = [];
                    resolve(nodes);
                }

            }
        }
    },
]);

const categoryForm = ref({
    status:1
});
const categoryFields = ref([
    {
        label:'分类名称',
        type:'input',
        key:'categoryName',
        required: true,
        placeholder:'请输入分类名称',
        message:'请输入分类名称',
        event:'blur',
    },
    {
        label:'上级',
        type:'cascader',
        key:'parentId',
        required: false,
        placeholder:'请选择上级',
        options:[],
        props:{
            lazy: true,
            emitPath:false,
            checkStrictly: true,// 设置父子节点取消选中关联，从而达到选择任意一级选项的目的
            async lazyLoad(node, resolve) {
                const { level } = node;
                try {
                    if(level === 0){
                        const res = await investmentProjects.getCategory({projectId:getProjectId,pid:0});
                        let nodes = [];
                        res.data.forEach(item=>{
                            nodes.push({
                                // value: item.projectId+'_'+item.categoryId,
                                value: item.categoryId,
                                label: item.categoryName,
                                leaf: level >= 3
                            })
                        });
                        resolve(nodes)
                    }
                    if(level > 0){
                        // const res = await investmentProjects.getCategory({projectId:getProjectId,pid:node.value.split('_')[1]});
                        const res = await investmentProjects.getCategory({projectId:getProjectId,pid:node.value});
                        let nodes = [];
                        res.data.forEach(item=>{
                            nodes.push({
                                value: item.categoryId,
                                label: item.categoryName,
                                leaf: level >= 3
                            })
                        });
                        resolve(nodes)
                    }
                }catch (e) {
                    let nodes = [];
                    resolve(nodes);
                }

            }
        }
    },
    {
        label:'备注说明',
        type:'textarea',
        key:'remark',
        rows:5,
        required: false,
        placeholder:'请输入分类名称',
    },
    {
        label:'启用状态',
        type:'switch',
        key:'status',
        required: false,
    },
    {
        label:'排序',
        type:'input',
        key:'sort',
        required: false,
        placeholder:'请输入排序'
    },
]);

const editCategoryForm = reactive({
    categoryId:'',
    categoryName:'',
    parentId:'',
    remark:'',
    status:'',
    sort:'',
    projectId:'',
    parentCategoryName:'',
    total:''
});

const editCategoryFields = ref([
    {
        label:'项目名称',
        type:'input',
        key:'projectName',
        required: false,
        width:300,
        disabled:true,
        placeholder:getProjectName,
    },
    {
        label:'营收类别',
        type:'input',
        key:'categoryName',
        width:300,
        placeholder:'请输入营收类别',
        message:'请输入营收类别',
        event:'blur'
    },
    {
        label:'父级分类名称',
        type:'input',
        key:'parentCategoryName',
        required: false,
        width:300,
        disabled:true,
        placeholder:'',
    },
    {
        label:'总额',
        type:'input',
        key:'total',
        required: false,
        width:300,
        disabled:true,
        placeholder:'',
    },
]);

/**
 * 新增营收分类
 * @param param
 * @param callback
 * @param err_callback
 */
const addCategory = (param,callback,err_callback) => {
    investmentProjects.addCategory(param).then(res=>{
        if(res.code === '200'){
            if(callback)callback(res);
        }else{
            if(err_callback)err_callback(res);
        }
    });
}

/**
 * 编辑类别
 * @param param
 * @param callback
 * @param err_callback
 */
const editCategory = (param,callback,err_callback) => {
   investmentProjects.editCategory(param).then(res=>{
        if(res.code === '200'){
            if(callback)callback(res);
        }else{
            if(err_callback)err_callback(res);
        }
    });
}

/**
 * 删除类别
 * @param categoryId
 * @param callback
 */
const deleteCategory = (categoryId,callback) => {
    investmentProjects.deleteCategory(categoryId).then(res=>{
        if(res.code === '200'){
          if(callback)callback();
        }else{
            ElMessage.error('删除失败!');
        }
    });
}

/**
 * 成功
 */
const onSuccess = () => {
    getYear(getProjectId);
    getRevenuePage(getProjectId);
}

/**
 * 查询营收分类
 */
const getCategory = () => {
    investmentProjects.getCategory({projectId:getProjectId,pid:0}).then(res=>{
      if(res.code === '200'){
          res.data.forEach(item=>{
              categoryFields.value[1].options = [];
              categoryFields.value[1].options.push({
                    value: item.categoryId,
                    label: item.categoryName
              });
              fields.value[3].options = [];
              fields.value[3].options.push({
                  value: item.categoryId,
                  label: item.categoryName
              });
          });
      }
    });
}

/**
 * 获取年份
 * @param projectId
 */
const getYear = (projectId) => {
  investmentProjects.getYear(projectId).then(res => {
    if (res.code === '200') {
      tableOption.value = [
        // { label: "项目名称", prop: "projectName",width:'150px' },
        { label: "营收类别", prop: "categoryName", minWidth: 100, slot: true },
        { label: "上级名称", prop: "parentCategoryName", minWidth: 120, slot: true },
        { label: "创建时间", prop: "createTime", minWidth: 150 },
        { label: "合计", prop: "total", minWidth: 100 },
      ]
      if (res.data) {
        res.data.forEach(item => {
          tableOption.value.push({
            label: item + '年',
            prop: 'amount' + item,
            minWidth: 100
          });
        });
      }
      tableOption.value.push({
        label: '操作',
        slot: true,
        width: 250,
        overHidden: false,
        slotName: 'buttons',
        fixed: 'right'
      });
    }
  });
}

/**
 * 格式化数据
 * @private
 */
const _initData = (data) => {
    if(!data || (data instanceof  Array && data.length === 0)){
        return [];
    }
    data.forEach(item=>{
        item.cash.forEach(subItem=>{
            item['amount'+subItem.year] = subItem.amount;
        });
        if(item.childList){
            _initData(item.childList);
        }
    });
    return data;
}

/**
 * 获取项目现金流表
 */
const getRevenuePage = (projectId) => {
    investmentProjects.getRevenuePage(projectId).then(res=>{
        if(res.code === '200'){
            tableData.value = _initData(res.data);
        }
    });
}

/**
 * 编辑类别
 * @param row
 */
const publicFormPopupRef3 = ref(null);
const onEditCategory = (row) => {
  publicFormPopupRef3.value.open(row);
}

/**
 * 编辑金额
 * @param row
 */
const editAmountPopupRef = ref(null);
const onEditAmount = (row) => {
    editAmountPopupRef.value.open(row);
}

/**
 * 删除
 * @param row
 */
const delProjectInvestmentRevenuePopupRef = ref(null);
const onDelete = (row) => {
    ElMessageBox.confirm(
        '确认删除吗?',
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then((action) => {
            if(action === 'confirm'){
                deleteCategory(row.categoryId,()=>{
                    ElMessage({
                        type: 'success',
                        message: '删除成功!',
                    });
                    getCategory();
                    // getYear(getProjectId);
                    getRevenuePage(getProjectId);
                });
            }
        })
   // delProjectInvestmentRevenuePopupRef.value.open(row);
}

/**
 * 新增现金流量表
 */
const publicFormPopupRef = ref(null);
const addCashFlow = () => {
    publicFormPopupRef.value.open();
}

/**
 * 新增类别
 */
const publicFormPopupRef2 = ref(null);
const adCategory = () => {
    publicFormPopupRef2.value.open();
}

/**
 * 导出
 */
const onExport = () => {
    investmentProjects.exportCategory({projectId:getProjectId}).then(res=>{
        if(res){
            exportExcelFile(res,'现金流量表');
        }
    });
}

/**
 * 现金流量表弹窗确认
 * @param form
 * @param isLoading
 */
const onCashflowStatementConfirm = (form,isLoading) => {
    isLoading.value = true;
    let params = {
        categoryId:form.categoryId,
        cash:[
            {
                amount:form.amount,
                year:form.year
            }
        ]
    }
    investmentProjects.editAndAddCashFlowOne(params).then(res=>{
        if(res.code === '200'){
            isLoading.value = false;
            publicFormPopupRef.value.close();
            ElMessage.success('新增成功!');
            getYear(getProjectId);
            getRevenuePage(getProjectId);// getProjectId
        }
    });
}

const visible = ref(false);
const onConfirm = () => {

}

/**
 * 模版下载
 */
const templateDownload = () => {
    costEstimationApi.mb({type:2}).then(res=>{
        if(res){
            exportExcelFile(res,'现金流量表模版');
        }
    });
}

/**
 * 导入
 */
const importExcel = () => {
    visible.value = true;
}

/**
 * 上传excel
 * @param file
 */
const uploadFile = (file) => {
    const loading = ElLoading.service({
        lock: true,
        text: "Loading",
        background: "rgba(0, 0, 0, 0.7)",
    });
    let uploadFile = new FormData();
    uploadFile.append("file", file.file);
    investmentProjects.importExcel(uploadFile,getProjectId).then(res=>{
        if (res.code === '200') {
            loading.close();
            ElMessage.success("上传成功!");
            visible.value = false;
            getYear(getProjectId);
            getRevenuePage(getProjectId);// getProjectId
        }else{
            loading.close();
            ElMessage.error("上传失败,请联系管理员!");
        }
    });
}

onMounted(()=>{
    getYear(getProjectId);
    getRevenuePage(getProjectId);// getProjectId
})
</script>

<style lang="scss" scoped>
.delete-icon{
  width: 20px;
  height: 20px;
  cursor: pointer;
}
</style>
